package com.twan.base.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.AdapterView;

import com.android.business.adapter.DataAdapteeImpl;
import com.android.business.adapter.DataAdapterInterface;
import com.android.business.entity.UserInfo;
import com.android.business.exception.BusinessException;
import com.example.dhcommonlib.util.PreferencesHelper;
import com.mm.dss.demo.MyLoginActivity;
import com.mm.dss.demo.MyMainActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.twan.base.R;
import com.twan.base.adapter.BaseRecyclerAdapter;
import com.twan.base.adapter.SmartViewHolder;
import com.twan.base.api.Api;
import com.twan.base.app.BaseActivity;
import com.twan.base.entity.ConnectBean;
import com.twan.base.entity.JianKongBean;
import com.twan.base.entity.JianKongBeanConvert;
import com.twan.base.network.ZyCallBack;
import com.twan.base.util.RxPermissionsUtil;
import com.twan.base.util.SPUtils;
import com.twan.base.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * @author Twan
 * @date 2019/4/24
 */
public class MonitorActivity extends BaseActivity {
    @BindView(R.id.refreshLayout) SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.recycler_view) RecyclerView mRecyclerView;

    private int pageIndex =1;
    List<JianKongBeanConvert> mddddd = new ArrayList<>();
    BaseRecyclerAdapter<JianKongBeanConvert> mAdpater;

    @Override
    protected int getLayout() {
        return R.layout.activity_monitor;
    }

    @Override
    protected void initEventAndData() {
        initRefresh();
        initData();
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        title.setText("监控中心");
    }

    private void initRefresh() {
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(mContext));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        //mRecyclerView.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdpater = new BaseRecyclerAdapter<JianKongBeanConvert>(mddddd, R.layout.item_monitor) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, JianKongBeanConvert model, final int position) {
                holder.text(R.id.tv_desc, model.getTypeName()+" - "+model.getSbName());
            }
        });
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                dataClear();
                initData();
            }
        });
        mAdpater.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                RxPermissionsUtil.requestPermission(MonitorActivity.this, new RxPermissionsUtil.PermissionListener() {
                    @Override
                    public void onSucces() {
                        //Router.newIntent(MonitorActivity.this).to(com.mm.dss.demo.LoginActivity.class).launch();
                        JianKongBeanConvert model = mddddd.get(position);
                        startServer(model.getSbId());
                    }
                }, Manifest.permission.READ_PHONE_STATE);
            }
        });
    }

    private void dataClear(){
        pageIndex=1;
        mddddd.clear();
        mAdpater.refresh(mddddd);
    }

    protected void initData() {
        Api.getApiService().getJianKong(SPUtils.getCustomId()).enqueue(new ZyCallBack<JianKongBean>(mRefreshLayout) {
            @Override
            public void doSuccess() {
                JianKongBean bean = mData;
                if (bean.getList() != null && bean.getList().size() > 0) {
                    if (pageIndex ==1){
                        dataClear();
                    }
                    mddddd.addAll(convert(bean.getList()));
                    mAdpater.refresh(mddddd);
                }
            }
        });
    }

    private ArrayList<JianKongBeanConvert> convert(ArrayList<JianKongBean.JianKong> list){
        ArrayList<JianKongBeanConvert> data = new ArrayList();
        for (JianKongBean.JianKong bean : list){
            for (JianKongBean.Shebei shebei: bean.getShebei()) {
                JianKongBeanConvert jbc = new JianKongBeanConvert();
                jbc.setSbId(shebei.getSbId());
                jbc.setSbName(shebei.getSbName());
                jbc.setTypeId(bean.getTypeId());
                jbc.setTypeName(bean.getTypeName());

                data.add(jbc);
            }
        }
        return data;
    }

    private void startServer(String sbid){
        Api.getApiService().sbDetail(SPUtils.getCustomId(),sbid).enqueue(new ZyCallBack<ConnectBean>() {
            @Override
            public void doSuccess() {
                ConnectBean bean = mData;
                if (bean != null){
                    //startConnect(bean);
                    Intent intent = new Intent(mContext, MyLoginActivity.class);
                    intent.putExtra("ip",bean.getSzIp());
                    intent.putExtra("port",bean.getnPort());
                    intent.putExtra("username",bean.getSzUsername());
                    intent.putExtra("password",bean.getSzPassword());
                    intent.putExtra("cameraid",bean.getSzCameraId());
                    mContext.startActivity(intent);
                }
            }
        });
    }

//    private void startConnect(final ConnectBean bean){
//        try {
//            final DataAdapterInterface dataAdapterInterface = DataAdapteeImpl.getInstance();
//            dataAdapterInterface.createDataAdapter("com.android.business.adapter.DataAdapteeImpl");
//            dataAdapterInterface.initServer(bean.getSzIp(), Integer.parseInt(bean.getnPort()));
//
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
//                    String clientMac = tm.getDeviceId();
//                    UserInfo info = null;
//                    try {
//                        info = dataAdapterInterface.login(bean.getSzUsername(), bean.getSzPassword(), "1", clientMac, 2);
//                    } catch (BusinessException e) {
//                        e.printStackTrace();
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    if(info != null) {
//                        Object groupid=  info.getExtandAttributeValue("groupId");
//                        String strGroupID = "";
//                        if (groupid instanceof String) {
//                            strGroupID = (String) groupid;
//                        } else if(groupid instanceof Long) {
//                            strGroupID = ((Long)groupid).toString();
//                        }
//                        PreferencesHelper.getInstance(getApplicationContext()).set("USER_GROUPID", strGroupID);
//                    }
//                    Message msg = new Message();
//                    msg.what = 0;
//                    msg.obj = (info != null);
//                    handler.sendMessage(msg);
//                }
//            }).start();
//        } catch (BusinessException e) {
//            ToastUtil.error("登陆监控服务器失败："+e.getMessage());
//        }
//    }
//
//    @SuppressLint("HandlerLeak")
//    private Handler handler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what) {
//                case 0:
//                    boolean ret = (Boolean) msg.obj;
//                    if(ret) {
//                        Intent intent = new Intent(mContext, MyMainActivity.class);
//                        mContext.startActivity(intent);
//                        finish();
//                    } else {
//                        ToastUtil.error("登陆监控服务器失败");
//                    }
//                    break;
//            }
//        }
//    };
}
